package com.itheima.web.controller.factory;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@Controller
@RequestMapping("/cargo/factory")
public class FactoryController extends BaseController {
    @Reference
    private FactoryService factoryService;

    //分页查询
    @RequestMapping(value = "/list", name = "公司页面分页展示")
    public String list(@RequestParam(name = "page", defaultValue = "1") int pageNum,
                             @RequestParam(name = "pageSize", defaultValue = "5") int pageSize) {

        FactoryExample factoryExample = new FactoryExample();
        List<Factory> list = factoryService.findAll(factoryExample);
        PageInfo pageInfo = factoryService.findByPage(pageNum, pageSize,factoryExample);
        request.setAttribute("page", pageInfo);
        return "cargo/factory/factory-list";
    }

    @RequestMapping(value = "/toAdd", name = "进入新增页面")
    public String toAdd() {
        List<Factory> ctypeList = factoryService.findCtype();
        request.setAttribute("ctypeList", ctypeList);
        return "cargo/factory/factory-edit";
    }

    @RequestMapping(value = "/toUpdate", name = "进入修改页面")
    public String toUpdate(String id) {
        List<Factory> ctypeList = factoryService.findCtype();
        Factory factory = factoryService.findById(id);
        request.setAttribute("ctypeList", ctypeList);
        request.setAttribute("factory", factory);
        return "cargo/factory/factory-edit";
    }

    @RequestMapping(value = "/edit",name = "新增或修改厂家")
    public String edit(Factory factory) {
        if (StringUtils.isEmpty(factory.getId())) {
            factory.setId(UUID.randomUUID().toString());

            factory.setCreateBy(getLoginUser().getCreateBy());
            factory.setCreateDept(getLoginUser().getCreateDept());
            factory.setCreateTime(new Date());
            factory.setUpdateTime(new Date());

            factoryService.save(factory);
        } else {
            factory.setUpdateBy(getLoginUser().getUpdateBy());
            factory.setUpdateTime(new Date());
            factoryService.update(factory);
        }
        return "redirect:/cargo/factory/list.do";
    }

    @RequestMapping(value = "/delete", name = "删除厂家")
    public String delete(String id) {
        factoryService.delete(id);
        return "redirect:/cargo/factory/list.do";
    }

}
